package com.yimi.yinhepda.views.unload_module;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.pda.ym.base.BaseActivity;
import com.pda.ym.callbacks.UICallBack;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.FastClick;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.entity.bean.AddEntity;
import com.yimi.yinhepda.event.CountEvent;
import com.yimi.yinhepda.event.ScanResult;
import com.yimi.yinhepda.utils.CheckNetTimeUtil;
import com.yimi.yinhepda.utils.Common;
import com.yimi.yinhepda.utils.UcWaybillValidate;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import static com.yimi.yinhepda.views.unload_module.UnloadScanActivity.chaoChangJian;
import static com.yimi.yinhepda.views.unload_module.UnloadScanActivity.yiXingJian;

/**
 * 添加装卸车扫描界面
 *
 * @author lj
 */
public class AddBillcodeActivity extends BaseActivity {
    private EditText load_addchildwaybill_ed;
    private Button manual_add_btn;
    private ListView add_chidlwaybill_listview;
    private TextView manaul_add_count, num;
    private Button add_childwaybill_back, add_childwaybill_ok;
    /**
     * 1-装车，2-卸车，3-跨越卸车
     */
    private int operTypeCode;
    private MyAdapter mMyAdapter;
    private List<AddEntity> dataList = new ArrayList<AddEntity>();
    private boolean isFirstScan;

    public AddBillcodeActivity() {
        super(true);
    }

    @Override
    public void handleBarCode(String result) {
        load_addchildwaybill_ed.setText(result);
        load_addchildwaybill_ed.setSelection(result.length());

        long scanLastTime = sharedPreferUtil.getLongValue(Common.SCAN_LAST_TIME);
        long currentTime = System.currentTimeMillis();
        if (isFirstScan || currentTime - scanLastTime > 1000 * 300) {
            isFirstScan = false;
            //每次进入界面校验网络时间,或者扫描时间超过五分钟
            String compCode = SharedPreferUtil.getInstance().getCompanyCode();
            String empCode = SharedPreferUtil.getInstance().getWorkNum();
            String pwd = SharedPreferUtil.getInstance().getPwd();
            CheckNetTimeUtil.checkNetworkTime(this, compCode, empCode, pwd, false, new UICallBack() {
                @Override
                public void onError(String msg) {
                    if (msg.equals(Constants.PLEASE_CHECK_NET)) {
                        doScan(load_addchildwaybill_ed.getText().toString().trim());
                    }
                }

                @Override
                public void onSuccess(Object obj) {
                    doScan(load_addchildwaybill_ed.getText().toString().trim());
                }
            });
        } else {
            doScan(load_addchildwaybill_ed.getText().toString().trim());
        }
    }

    //处理扫描
    private void doScan(String result) {
        //本地记录扫描最后时间
        sharedPreferUtil.setLongValue(Common.SCAN_LAST_TIME, System.currentTimeMillis());

        if (!StringUtils.isWaybillNo(result) && !StringUtils.isPackgeNo(result) && !UcWaybillValidate.validate(result)
                && !StringUtils.isKuaYueWaybillNo(result)) {
            SoundVibratorManager.playSound(2);
            showToast("单号或包号不规范!(" + result + ")");
            return;
        }
        if (operTypeCode == 1) {
            //装车扫描
            EventBus.getDefault().post(new ScanResult(result, 5, 5));
        } else if (operTypeCode == 2) {
            //卸车扫描
            EventBus.getDefault().post(new ScanResult(result, 7, 7));
        } else if (operTypeCode == 3) {
            //跨越卸车
            //发送消息处理扫描结果
            EventBus.getDefault().post(new ScanResult(result, 3, 3));
        }
    }

    private synchronized void addUnloadCount() {
        //设置未上传数
        num.setText((Integer.parseInt(num.getText().toString()) + 1) + "");
    }

    //计算多少票多少件
    private void excCount() {
        Set<String> set = new HashSet<String>();
        for (AddEntity item : dataList) {
            set.add(item.getWaybillNum());
        }
        manaul_add_count.setText(set.size() + "/" + dataList.size());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_childbillway);
        initView();
        initData();
        //注册事件
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册事件
        EventBus.getDefault().unregister(this);
    }

    private void initData() {
        isFirstScan = true;
        operTypeCode = getIntent().getIntExtra("operTypeCode", 1);

        mMyAdapter = new MyAdapter(this, dataList);
        add_chidlwaybill_listview.setAdapter(mMyAdapter);

        if (operTypeCode == 3) {
            num.setVisibility(View.GONE);
        } else {
            num.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public String getPageName() {
        return "手动添加单号";
    }

    private void initView() {
        ((TextView) findViewById(R.id.title)).setText("手动添加单号");
        num = findViewById(R.id.num);

        load_addchildwaybill_ed = findViewById(R.id.load_addchildwaybill_ed);

        manual_add_btn = findViewById(R.id.manual_add_btn);
        manual_add_btn.setOnClickListener(this);

        add_chidlwaybill_listview = findViewById(R.id.add_chidlwaybill_listview);

        manaul_add_count = findViewById(R.id.manaul_add_count);

        add_childwaybill_back = findViewById(R.id.add_childwaybill_back);
        add_childwaybill_back.setOnClickListener(this);
        add_childwaybill_ok = findViewById(R.id.add_childwaybill_ok);
        add_childwaybill_ok.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (FastClick.isFastClick()) {
            return;
        }

        switch (v.getId()) {
            case R.id.manual_add_btn:
                String waybillNo = load_addchildwaybill_ed.getText().toString().trim();
                if (TextUtils.isEmpty(waybillNo)) {
                    SoundVibratorManager.playSound(2);
                    showToast("请先输入需要手动添加的单号！");
                    return;
                }
                handleBarCode(waybillNo);
                break;
            case R.id.add_childwaybill_back:
                finish();
                break;
            case R.id.add_childwaybill_ok:
                finish();
                break;
            default:
                break;
        }
    }


    static class MyAdapter extends BaseAdapter {
        private Context context;
        private List<AddEntity> dataList;

        public MyAdapter(Context context, List<AddEntity> dataList) {
            this.context = context;
            this.dataList = dataList;
        }

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            MyHolder mHolder;
            if (convertView == null) {
                mHolder = new MyHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.activity_add_childbillway_listviewitem, null);
                mHolder.sequencyNum = convertView.findViewById(R.id.sequencynum);
                mHolder.waybillNum = convertView.findViewById(R.id.waybillnum);
                mHolder.childwayBillNum = convertView.findViewById(R.id.childwaybillnum);
                convertView.setTag(mHolder);
            } else {
                mHolder = (MyHolder) convertView.getTag();
            }
            mHolder.sequencyNum.setText(position + 1 + "");
            mHolder.waybillNum.setText(dataList.get(position).getWaybillNum());
            mHolder.childwayBillNum.setText(dataList.get(position).getChildwayBillNum());

            return convertView;
        }
    }

    static class MyHolder {
        TextView sequencyNum;
        TextView waybillNum;
        TextView childwayBillNum;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(CountEvent countEvent) {
        num.setText(countEvent.getCount() + "");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent2(ScanResult event) {
        if (event.getOperType() == 1 && event.getOperSource() == 3) {
            //跨越手动添加卸车扫描
            String result = event.getResult();
            dataList.add(new AddEntity(result.substring(0, result.length() - 8), result));
            mMyAdapter.notifyDataSetChanged();
            //计算多少票多少件
            excCount();
            SoundVibratorManager.playSound(1);
        } else if ((event.getOperSource() == 5 && event.getOperType() == 6) ||
                (event.getOperSource() == 7 && event.getOperType() == 8)) {
            //手动装卸车
            dataList.add(new AddEntity(event.getWaybillNo(), event.getResult()));
            mMyAdapter.notifyDataSetChanged();
            //计算多少票多少件
            excCount();
            //未扫描数+1
            addUnloadCount();
            load_addchildwaybill_ed.setText("");
            if(event.getOperSource() == 7 && event.getOperType() == 8){
                //卸车手动添加
                if (chaoChangJian != null && yiXingJian.isChecked()) {
                    SoundVibratorManager.playSound(7);
                } else if (chaoChangJian != null) {
                    SoundVibratorManager.playSound(4);
                } else if (yiXingJian.isChecked()) {
                    SoundVibratorManager.playSound(6);
                } else {
                    SoundVibratorManager.playSound(1);
                }
            }else{
                //装车手动添加
                SoundVibratorManager.playSound(1);
            }
        } else if (event.getOperSource() == 9 && event.getOperType() == 9) {
            //快递装卸车撤销
            Iterator<AddEntity> it = dataList.iterator();
            while (it.hasNext()) {
                AddEntity entity = it.next();
                if (entity.getChildwayBillNum().equals(event.getResult())) {
                    it.remove();
                }
            }
            mMyAdapter.notifyDataSetChanged();
            //计算多少票多少件
            excCount();
            load_addchildwaybill_ed.setText("");
        }
    }
}
